<template>
  <div
    v-if="!initializing"
    class="vc-component"
    :style="visual.parseStyle(currNode.currStyle)"
  >
    <el-select
      v-model="currValue"
      class="vc-select"
      @change="handleChange"
      v-bind="options"
    >
      <el-option
        v-for="item in dataList"
        :key="item.key"
        :value="item.key"
        :label="item.value"
      />
    </el-select>
  </div>
</template>

<script setup>
import { ref, computed, inject, getCurrentInstance, onMounted, nextTick } from 'vue';
import visual from "@/visual/js/visual";
import { getDictionary } from '@/utils/system';
import api from "@/http/api";
import EventHandler from "@/visual/js/event";
import { useFormItem } from "element-plus";

const props = defineProps({
  node: Object
});
const initializing = ref(true);
const pageData = inject("pageData", ref({}));
const formItem = useFormItem();
const currNode = ref(props.node);
const currValue = ref([]);
const currDictCode = ref('');
const currDataModelId = ref('');
const currDMValue = ref('');
const currDMLabel = ref('');
const dataList = ref([]);
const eventHandler = new EventHandler(
  inject('eventHandler', Function, true),
  getCurrentInstance(),
  currNode.value
);

const options = computed(() => {
  const compStyle = currNode.value.currCompStyle || {};
  const options = {};
  visual.addIfNotNull(options, compStyle, 'size');
  visual.addIfNotNull(options, compStyle, 'placeholder');
  visual.addIfNotNull(options, compStyle, 'effect');
  visual.addIfNotNull(options, compStyle, 'filterable');
  visual.addIfNotNull(options, compStyle, 'multiple');
  visual.addIfNotNull(options, compStyle, 'allow-create');
  visual.addIfNotNull(options, compStyle, 'fit-input-width');
  visual.addIfNotNull(options, compStyle, 'required');
  visual.addIfNotNull(options, compStyle, 'clearable');
  visual.addIfNotNull(options, compStyle, 'disabled');
  visual.addIfNotNull(options, compStyle, 'autocomplete');
  return options;
});

const loadDictionary = async(dictCode) => {
  dataList.value = dictCode ? await getDictionary(dictCode) : [];
};

const loadDataModelData = async(dataModelId, compStyle) => {
  if (!dataModelId) {
    dataList.value = [];
    return;
  }

  const res = await api.post('/codeless/data-model/' + dataModelId + '/list');
  let fieldValueOptions = [];
  (res.data && res.data).forEach(field => {
    fieldValueOptions.push({key: field[compStyle["value"]], value: field[compStyle["label"]]});
  });
  dataList.value = fieldValueOptions;
};

const init = async(styleId) => {
  initializing.value = true;
  visual.initStyle(currNode.value, styleId);
  const compStyle = currNode.value.currCompStyle || {};
  if (compStyle['dataSource'] === 'enum') {
    let optionList = [];
    (compStyle['enumValue'] || '').split(',').forEach(item => {
      optionList.push({key: item, value: item});
    });
    dataList.value = optionList;
  } else if (compStyle['dataSource'] === 'dict') {
    currDictCode.value = compStyle['dictCode'] || '';
    await loadDictionary(currDictCode.value);
  } else if (compStyle['dataSource'] === 'dataModel') {
    if (currDataModelId.value !== ''
        && (currDataModelId.value !== (compStyle['dataModelId'] || '')
          || currDMValue.value !== (compStyle['value'] || '')
          || currDMLabel.value !== (compStyle['label'] || ''))) {
      currDMValue.value = compStyle['value'] || '';
      currDMLabel.value = compStyle['label'] || '';
      await loadDataModelData(currDataModelId.value, compStyle);
    }
  }
  await nextTick(() => initializing.value = false);
};

const loadValue = async() => {
  const dataList = (await visual.loadData(currNode.value.compData, eventHandler, getData(), currNode.value)).data || [];
  const defaultValue = dataList.length > 0 && dataList[0]['内容'] || '';
  if (currNode.value.currCompStyle['multiple'] === true) {
    currValue.value = defaultValue ? defaultValue.split(',') : [];
  } else {
    currValue.value = defaultValue;
  }
  pageData.value[currNode.value.name] = defaultValue || '';
};

const handleChange = () => {
  if (currValue.value) {
    if (Array.isArray(currValue.value) && currValue.value.length > 0) {
      pageData.value[currNode.value.name] = currValue.value.join(',');
    } else if (typeof currValue.value === 'string') {
      pageData.value[currNode.value.name] = currValue.value;
    } else {
      pageData.value[currNode.value.name] = '';
    }
  } else {
    pageData.value[currNode.value.name] = '';
  }

  if (formItem && formItem.formItem) {
    formItem.formItem.validate('change');
  }

  eventHandler.trigger('变更事件');
};

const getData = () => {
  return {
    inputParam: currNode.value.inputParam,
    value: pageData.value[currNode.value.name]
  };
};

const changeStyle = (styleId) => {
  init(styleId);
};

const refresh = async() => {
  initializing.value = true;
  await loadValue();
  await nextTick(() => initializing.value = false);
};

onMounted(async() => {
  await init();
  await loadValue();
  await eventHandler.trigger('初始化事件');
});

defineExpose({ getData, changeStyle, refresh });
</script>

<style scoped>
.vc-select {
  min-width: 100px;
}
</style>